<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Session Mode - URU4500 Verify</title>
        <link rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
        <link rel="stylesheet"
            href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <script
            src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script
            src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script
            src="https://cdn.jsdelivr.net/npm/moment@2/min/moment.min.js"></script>
        <script
            src="https://cdn.jsdelivr.net/npm/moment-timezone@0.5.43/builds/moment-timezone-with-data.min.js"></script>
        <style>
        body { background: #f7fafd; }
        .card-profile { min-width: 280px; }
        .card-session { box-shadow: 0 0 14px #e8eaf3; }
        .counter-big { font-size: 2.4rem; font-weight: 800; }
    </style>
    </head>
    <body>
        {% include 'navbar.html' %}
        <div class="container py-5">
            <div class="row g-5">
                <div class="col-md-4">
                    <div class="card card-session mb-4">
                        <div class="card-body">
                            <h4 class="card-title mb-3">🎬 Session
                                Management</h4>
                            <div id="session-status"></div>
                            <form id="open-session-form" class="d-none">
                                <label>ชื่อ Session</label>
                                <input class="form-control mb-2"
                                    name="session_name" required>
                                <button class="btn btn-primary w-100"
                                    type="submit">เปิด Session ใหม่</button>
                            </form>
                            <button id="close-session-btn"
                                class="btn btn-danger w-100 d-none mt-2">ปิด
                                Session</button>
                            <hr>
                            <button id="reset-device-btn"
                                class="btn btn-warning col-md-12">
                                🔄 Reset Device
                            </button>
                            <script>
                        $("#reset-device-btn").click(function() {
                            Swal.fire({
                                title: "Reset Device?",
                                text: "ต้องการรีเซ็ตเครื่องอ่านลายนิ้วมือหรือไม่?",
                                icon: "warning",
                                showCancelButton: true,
                                confirmButtonText: "รีเซ็ต",
                                cancelButtonText: "ยกเลิก"
                            }).then((result) => {
                                if(result.isConfirmed){
                                    $.ajax({
                                        url: "/api/reset_device",
                                        type: "POST",
                                        success: function(res){
                                            if(res.success){
                                                Swal.fire("Success", res.msg, "success");
                                            }else{
                                                Swal.fire("Error", res.msg, "error");
                                            }
                                        },
                                        error: function(){
                                            Swal.fire("Error", "ไม่สามารถรีเซ็ต device ได้", "error");
                                        }
                                    });
                                }
                            });
                        });
                    </script>
                        </div>
                    </div>
                    <div class="card card-session mb-4">
                        <div class="card-body text-center">
                            <div>ผู้ที่ Verify แล้ว / ทั้งหมด</div>
                            <div>
                                <span id="count-verified"
                                    class="counter-big text-success">0</span>
                                /
                                <span id="count-all"
                                    class="counter-big text-dark">0</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="card card-session mb-4">
                        <div class="card-body">
                            <h4 class="mb-3">🔍 Verify นิ้วมือ (Session
                                Mode)</h4>
                            <button id="verify-scan-session"
                                class="btn btn-success w-100 mb-2">Scan &
                                Verify</button>
                            <div id="session-verify-result"></div>
                        </div>
                    </div>
                    <div class="card card-session">
                        <div class="card-body">
                            <h5>Log การ Verify ใน Session นี้</h5>
                            <table id="session-log-table"
                                class="table table-bordered table-striped"
                                style="width:100%;">
                                <thead>
                                    <tr>
                                        <th>เวลา</th>
                                        <th>รหัส</th>
                                        <th>ชื่อ-นามสกุล</th>
                                        <th>ชั้นปี</th>
                                        <th>สังกัด</th>
                                        <th>ผลลัพธ์</th>
                                        <th>รูปภาพ</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>
let sessionLogTable = $('#session-log-table').DataTable({
        columns: [
            { title: "เวลา" },
            { title: "รหัส" },
            { title: "ชื่อ-นามสกุล" },
            { title: "ชั้นปี" },
            { title: "สังกัด" },
            { title: "ผลลัพธ์", orderable: false, searchable: false },
            { title: "รูปภาพ", orderable: false, searchable: false }
        ],
        order: [[0, "desc"]]
    });

function loadSessionStatus() {
    $.get("/api/session_status", function(res){
        if(res.active){
            $("#session-status").html('<div class="alert alert-success">Session เปิดอยู่: <b>' + res.session.name + '</b></div>');
            $("#close-session-btn").removeClass("d-none");
            $("#open-session-form").addClass("d-none");
        } else {
            $("#session-status").html('<div class="alert alert-danger">Session ปิดอยู่</div>');
            $("#close-session-btn").addClass("d-none");
            $("#open-session-form").removeClass("d-none");
        }
    });
}

function loadSessionLog() {
    $.get("/api/session_users_logs", function(res){
        sessionLogTable.clear();
        let user_ids_verified = 0;
        res.users.forEach(u => {
            let imgTag = u.photo ? `<img src="data:image/jpeg;base64,${u.photo}" class="rounded-circle" style="width:40px;height:40px;">` : "";
            let status = u.verified ? `<span class="badge bg-success">✔ Verified</span>` : `<span class="badge bg-secondary">-</span>`;
            if(u.verified) user_ids_verified++;  // นับ user ที่ verified แล้ว
            let statusRow = status + " " + (u.score !== undefined && u.score !== null ? (({{ FP_SCORE_THRESHOLD }} - u.score) / {{ FP_SCORE_THRESHOLD }} * 100).toFixed(1) + "%" : "");
            sessionLogTable.row.add([
                u.verify_time ? moment.tz(u.verify_time, "UTC").format("YYYY-MM-DD HH:mm:ss") : "-",
                u.student_code,
                u.fullname,
                u.year,
                u.department,
                statusRow,
                imgTag
            ]);
        });
        sessionLogTable.draw();

        $("#count-verified").text(user_ids_verified);
        $("#count-all").text(res.users.length);
    });
}

$("#open-session-form").submit(function(e){
    e.preventDefault();
    let name = $(this).find("input[name='session_name']").val();
    $.ajax({
        url: "/api/open_session",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({name: name}),
        success: function(res){
            if(res.success){
                loadSessionStatus();
            }
        }
    });
});
$("#close-session-btn").click(function(){
    Swal.fire({
        title: "ปิด Session นี้?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: 'ปิด Session',
        cancelButtonText: 'ยกเลิก',
    }).then((result) => {
        if(result.isConfirmed){
            $.post("/api/close_session", {}, function(res){
                if(res.success){
                    loadSessionStatus();
                }
            }, "json");
        }
    });
});
$("#verify-scan-session").click(function(){
    $("#session-verify-result").html('<div class="alert alert-info">กำลังตรวจสอบนิ้วมือ ...</div>');
    $.ajax({
        url: "/api/session_verify",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function(res){
            if(res.success){
                let p = res.profile;
                let img = p.photo ? `<img src="data:image/jpeg;base64,${p.photo}" style="width:70px;height:70px;object-fit:cover;" class="rounded-circle mb-2">` : "";
                $("#session-verify-result").html(`
                    <div class="card card-profile p-2 mb-2">
                        <div class="row g-0">
                            <div class="col-3 align-self-center">${img}</div>
                            <div class="col-9">
                                <div class="card-body">
                                    <h5 class="card-title mb-1">${p.fullname}</h5>
                                    <div>รหัส: ${p.student_code}</div>
                                    <div>สังกัด: ${p.department}</div>
                                    <div>Score: <b>${res.score}</b></div>
                                </div>
                            </div>
                        </div>
                    </div>
                `);
            } else {
                $("#session-verify-result").html('<div class="alert alert-danger">'+res.error+'</div>');
            }
            loadSessionLog();
        }
    });
});
// Auto load
loadSessionStatus();
loadSessionLog();
setInterval(loadSessionLog, 3000); // ปรับเวลารีโหลดข้อมูล
</script>
    </body>
</html>
